package com.mop.core.es.dao.plugins.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lemon.core.common.lang.util.Assert;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lemon
 * @ClassName Mapping
 * @desc 修改字段和类型的
 * @Date 2019/1/5 13:15
 * @Version 1.0
 **/
public class Mapping {

    private String typeName;

    private List<MappingField> properties = new LinkedList<MappingField>();

    public String getTypeName() {
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }

    public List<MappingField> getProperties() {
        return properties;
    }

    public void setProperties(List<MappingField> properties) {
        this.properties = properties;
    }

    public void addMappingField(MappingField mappingField) {
        properties.add(mappingField);
    }

    @Override
    public String toString() {
        JSONObject mapping = new JSONObject();
        Assert.hasLength(typeName, "文档名称不可为空!");
        Assert.notNull(properties, "字段配置不可为空!");

        JSONObject docObj = new JSONObject();
        JSONObject propertiesObj = new JSONObject();
        for (MappingField field : properties) {
            JSONObject fieldObj = JSON.parseObject(field.toString());
            for (String fieldName : fieldObj.keySet()) {
                propertiesObj.put(fieldName, fieldObj.getJSONObject(fieldName));
            }
        }
        docObj.put("properties", propertiesObj);
        mapping.put(typeName, docObj);
        return mapping.toString();
    }
}
